<template>
	<div class="container-wrap">
		<description logo="iconfont icon-cunchuchi" :title="title" :desc="desc" />
		<el-card class="table-wrap" shadow="never">
			<div class="operation mb15">
				<span>
					<el-input clearable placeholder="请输入存储池名称" class="width-150" v-model="searchInput" @keyup.enter="search"></el-input>
					<el-button type="primary" class="ml10" @click="search">搜索</el-button>
				</span>
				<span>
					<el-button type="primary" @click="createStoragePool">创建</el-button>
					<el-button type="primary" :disabled="!selectRow" @click="storagePoolDiskManager">磁盘管理</el-button>
					<el-button type="danger" @click="deleteStoragePool" :disabled="!selectRow">删除</el-button>
					<el-button type="primary" @click="getPoolList">刷新</el-button>
				</span>
			</div>
			<el-table
				ref="tableRef"
				v-loading="state.storageTable.loading"
				:data="state.storageTable.data"
				border
				element-loading-text="数据加载中..."
				highlight-current-row
				row-key="id"
				height="calc(100vh - 455px)"
				@row-click="handleRowClick"
			>
				<el-table-column prop="poolName" label="名称" show-overflow-tooltip :min-width="150" />
				<el-table-column label="类型" show-overflow-tooltip :width="100">
					<template v-slot="{row}">
						<span>
							{{(poolTypeMap as any )[row.type]}}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="redundantMode" label="冗余模式" show-overflow-tooltip :min-width="150" />
				<el-table-column prop="pgNum" label="pg数" show-overflow-tooltip :min-width="70" />
				<el-table-column prop="pgpNum" label="pgp数" show-overflow-tooltip :min-width="70" />
				<el-table-column prop="rbdList" label="存储卷" :min-width="250">
					<template v-slot="{row}">
						<el-popover trigger="click" placement="top">
							<p v-for="item in row.rbdList" :key="item">{{ item }}</p>
							<template v-slot:reference>
								<div class="cursor-pointer">
									{{ row.rbdList?.join(',') }}
								</div>
							</template>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="文件系统" show-overflow-tooltip :min-width="200">
					<template v-slot="{row}">
						<span v-if="row.fileSystem">{{row.fileSystem}}</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="usedSize" label="存储用量" show-overflow-tooltip :min-width="150">
					<template #default="{row}">
						{{ formatUnits(row.usedSize) }}
					</template>
				</el-table-column>
				<el-table-column prop="totalSize" label="存储容量" show-overflow-tooltip :min-width="150">
					<template #default="{row}">
						{{ formatUnits(row.totalSize)  }}
					</template>
				</el-table-column>
				<el-table-column prop="isAvailable" label="是否可用" show-overflow-tooltip :width="100" >
					<template #default="{row}">
						<el-tag :type="row.isAvailable ? 'success' : 'danger'">
							{{ row.isAvailable ? '可用' : '不可用' }}
						</el-tag>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="state.storageTable.params.pageNum"
				v-model:page-size="state.storageTable.params.pageSize"
				@current-change="onHandleCurrentChange"
				@size-change="onHandleSizeChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.storageTable.total"
			>
			</el-pagination>
		</el-card>

		<el-dialog title="创建存储池" v-model="createStoragePoolVisible" :destroy-on-close="true" width="600px">
			<CreateStoragePool ref="createStoragePoolRef" />
			<template #footer>
				<el-button @click="createStoragePoolVisible = false">取消</el-button>
				<el-button type="primary" @click="handleCreatePool">确定</el-button>
			</template>
		</el-dialog>

		<el-dialog :title="storagePoolDiskTitle" :destroy-on-close="true" v-model="storagePoolDiskVisible" append-to-body width="900px">
			<StoragePoolDiskList :poolRow="selectRow"/>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, getCurrentInstance, onMounted, onUnmounted, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { storageTableState, storagePoolState } from './interface/index';
import { useStorageApi } from '/@/api/storage';
import { formatUnits } from '/@/utils/other';

const Description = defineAsyncComponent(() => import('/@/components/description/index.vue'));
const CreateStoragePool = defineAsyncComponent(() => import('./components/createStoragePool.vue'));
const StoragePoolDiskList = defineAsyncComponent(() => import('./components/storagePoolDiskList.vue'));

const storageApi = useStorageApi();
const title = '存储池';
const desc = '存储池是由一组物理磁盘组成的逻辑实体，用于管理和存储对象';
const storagePoolDiskTitle = computed(() => `存储池磁盘管理${selectRow.value?.poolName}`);
const selectRow = ref<storagePoolState | null>(null);
const poolTypeMap = {
	'1': '副本池',
	'3': '纠删码池',
};

let state = reactive<storageTableState>({
	storageTable: {
		loading: false,
		data: [],
		params: {
			pageNum: 1,
			pageSize: 10
		},
		total: 0
	}
});
const searchInput = ref('');

const handleRowClick = (row:storagePoolState) => {
	selectRow.value = row;
};
const search = () => {
	state.storageTable.params.poolName = searchInput.value;
	getPoolList(true);
};
const onHandleCurrentChange = () => {
	getPoolList(true);
};
const onHandleSizeChange = () => {
	getPoolList(true);
};
const getPoolList = (loading:boolean = false) => {
	loading && (state.storageTable.loading = true);
	if (loading) {
		state.storageTable.loading = true;
		tableRef?.value?.setCurrentRow();
	}
	storageApi.getPoolList({
		poolName: state.storageTable.params.poolName === '' ? undefined : state.storageTable.params.poolName,
		pageNo: state.storageTable.params.pageNum,
		pageSize: state.storageTable.params.pageSize
	}).then(res => {
		state.storageTable.data = res.data.records;
		state.storageTable.total = res.data.total;
	}).finally(() => {
		state.storageTable.loading = false;
	});
};
onMounted(() => {
	getPoolList(true);
});

// ws refresh list
const { proxy } = <any>getCurrentInstance();
proxy.mittBus.on('refresh-list', () => {
	getPoolList();
});
onUnmounted(() => {
	proxy.mittBus.off('refresh-list');
});

// createStoragePool
let createStoragePoolVisible = ref(false);
const createStoragePool = () => {
	createStoragePoolVisible.value = true;
};
const createStoragePoolRef = ref();
const handleCreatePool = () => {
	createStoragePoolRef.value.createStoragePool().then(() => {
		ElMessage.success('添加【新增存储池】任务成功');
		createStoragePoolVisible.value = false;
	}).catch(() => {});
};

// storagePoolDisk
let storagePoolDiskVisible = ref(false);
const storagePoolDiskManager = () => {
	storagePoolDiskVisible.value = true;
};

// deleteStoragePool
const tableRef = ref();
const deleteStoragePool = () => {
	ElMessageBox.confirm(`确认删除存储池${selectRow.value?.poolName}`, '系统提示', {
		cancelButtonText: '取消',
		confirmButtonText: '确定',
		type: 'warning'
	}).then(() => {
		storageApi.deleteStoragePool({ poolName: selectRow.value!.poolName }).then((res:any) => {
			if (res.code === 0) {
				ElMessage.success(`添加【删除存储池${selectRow.value?.poolName}】任务成功`);
				tableRef.value?.setCurrentRow();
				selectRow.value = null;
			}
		});
	});
};
</script>

<style lang="scss" scoped>
.vertical-middle{
	i,span{
		display: inline-block;
		vertical-align: middle;
	}
}
</style>